package com.fattyCorps.account.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fattyCorps.account.exception.TokenErrorException;
import com.fattyCorps.account.mapper.AccountMapper;
import com.fattyCorps.account.obj.db.Account;
import com.fattyCorps.account.obj.msg.HttpStatus;
import com.fattyCorps.account.obj.msg.SRet;
import com.fattyCorps.account.obj.msg.server.login.SLoginMsg;
import com.fattyCorps.account.uitl.AccJwtUtils;
import com.fattyCorps.account.uitl.BcryptUtils;
import com.fattyCorps.common.obj.msg.server.login.SInfoMsg;
import com.fattyCorps.common.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class LoginService {

    public static final String JWT_SECRET = "vcf&*acc$ff";

    @Autowired
    AccountMapper accountMapper;

    // 注册功能
    public SRet reg(String account, String password) {
        // 使用正则表达式判断账号格式是否正确
        // 字母、数字、特殊符号组成，账号字数限制5-20个字符 特殊符号仅限 @ $ ^ ! ~ , . *
        if (!checkAccount(account)) {
            return SRet.error(HttpStatus.REG_ACCOUNT_FORM_ERROR.getCode(), HttpStatus.REG_ACCOUNT_FORM_ERROR.getMsg());
        }

        // 使用正则表达式判断密码格式是否正确
        // 字母、数字、特殊符号组成，账号字数限制8-16个字符 特殊符号仅限 @ $ ^ ! ~ , . *
        if (!checkPassword(password)) {
            return SRet.error(HttpStatus.REG_PASSWORD_FORM_ERROR.getCode(), HttpStatus.REG_PASSWORD_FORM_ERROR.getMsg());
        }

//        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        String md5Password = BcryptUtils.encode(password);

        Account accountObj = new Account();
        accountObj.setAccount(account);
        accountObj.setPassword(md5Password);

        try {
            accountMapper.insert(accountObj);
        } catch (Exception e) {
            return SRet.error(HttpStatus.REG_DUPLICATE_ACCOUNT_ERROR.getCode(), HttpStatus.REG_DUPLICATE_ACCOUNT_ERROR.getMsg());
        }

        return SRet.success();
    }

    public SRet login(String account, String password) {
        SLoginMsg sLoginMsg = new SLoginMsg();
        Account accountObj = getAccount(account);

        if (accountObj == null) {
            // 没有这个账号
            return SRet.error(HttpStatus.LOGIN_FIND_ACCOUNT_ERROR.getCode(), HttpStatus.LOGIN_FIND_ACCOUNT_ERROR.getMsg());
        }

        if (BcryptUtils.match(password, accountObj.getPassword())) {
            // 相等 生成token 返回
            String token = JwtUtils.createToken(AccJwtUtils.ACC_ID_NAME, accountObj.getId(), JWT_SECRET);
            sLoginMsg.setToken(token);
            return SRet.success(sLoginMsg);
        }

        return SRet.error(HttpStatus.LOGIN_PASSWORD_ERROR.getCode(), HttpStatus.LOGIN_PASSWORD_ERROR.getMsg());

    }

    public SRet modify(String account, String rawPw, String newPw) {
        Account accountObj = getAccount(account);

        if (accountObj == null) {
            // 没有这个账号
            return SRet.error(HttpStatus.LOGIN_FIND_ACCOUNT_ERROR.getCode(), HttpStatus.LOGIN_FIND_ACCOUNT_ERROR.getMsg());
        }

        if (!checkPassword(newPw)) {
            return SRet.error(HttpStatus.REG_PASSWORD_FORM_ERROR.getCode(), HttpStatus.REG_PASSWORD_FORM_ERROR.getMsg());
        }

        if (BcryptUtils.match(rawPw, accountObj.getPassword())) {
            // 相等 修改密码
            accountObj.setPassword(BcryptUtils.encode(newPw));
            accountMapper.updateById(accountObj);
            return SRet.success();
        }

        return SRet.error(HttpStatus.LOGIN_PASSWORD_ERROR.getCode(), HttpStatus.LOGIN_PASSWORD_ERROR.getMsg());
    }

    public Account getAccount(String account) {
        QueryWrapper<Account> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.eq("account", account);
        return accountMapper.selectOne(objectQueryWrapper);
    }

    public SInfoMsg info(String token) {
        Integer id = JwtUtils.getIdByToken(token, AccJwtUtils.ACC_ID_NAME, LoginService.JWT_SECRET);
        if (id <= 0) {
            throw new TokenErrorException();
        }

        SInfoMsg msg = new SInfoMsg();
        msg.setId(id);
        return msg;
    }

    //校验创建事件页面账号格式
    private boolean checkAccount(String accountNumber) {
        String valicateAccount = "^[\\w@\\$\\^!~,.\\*]{5,20}+$";
        Pattern pattern = Pattern.compile(valicateAccount);
        Matcher matcher = pattern.matcher(accountNumber);
        boolean matches = matcher.matches();
        if (matches) {
            return true;
        } else {
            return false;
        }
    }

    //密码校验：
    private boolean checkPassword(String passWord) {
        String valicatePassword = "^[\\w@\\$\\^!~,.\\*]{8,16}+$";
        Pattern pattern = Pattern.compile(valicatePassword);
        Matcher matcher = pattern.matcher(passWord);
        boolean matches = matcher.matches();
        if (matches) {
            return true;
        } else {
            return false;
        }
    }
}
